package pkg.andru.concurrent;

import java.util.concurrent.atomic.AtomicInteger;

import android.os.Process;

/**
 * some convenience method for thread use
 * 
 * @author frodo
 * 
 */
public class ThreadUtils {

    static AtomicInteger mCounter = new AtomicInteger(0);

    /**
     * run some short method in another thread, the thread priority is
     * {@link Process#THREAD_PRIORITY_BACKGROUND}, and thread is auto start
     * 
     * @param runnerName
     *            thread name, can be null, if is null, will use bg#number as
     *            the thread name
     * @param runner
     * 
     */
    public static void runInBackgroundThread(String runnerName, Runnable runner) {
        if (runner != null) {
            final String tname = runnerName == null ? ("bg #" + mCounter.incrementAndGet()) : runnerName;
            final Runnable temp = runner;
            new Thread() {
                @Override
                public void run() {
                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                    setName(tname);
                    temp.run();
                }
            }.start();
        }
    }

}
